package jp.co.baka.gae.example.controller.view.bbs;

import java.util.ConcurrentModificationException;
import java.util.Date;

import jp.co.baka.gae.example.model.BbsMessage;
import jp.co.baka.gae.example.service.BbsService;
import jp.co.baka.gae.example.util.PerformanceChecker;
import jp.co.baka.gae.lib.MyController;

import org.slim3.controller.Navigation;
import org.slim3.controller.validator.Validators;
import org.slim3.datastore.Datastore;
import org.slim3.util.BeanUtil;

import com.google.appengine.api.datastore.DatastoreService;
import com.google.appengine.api.datastore.DatastoreServiceFactory;
import com.google.appengine.api.datastore.EntityNotFoundException;
import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.KeyFactory;
import com.google.appengine.api.datastore.Transaction;

public class InsertController extends MyController {


    @Override
    public Navigation run() {

        if (!validate()) {
            return forward(basePath);
        }

        PerformanceChecker timer = PerformanceChecker.get();

        Long id = BbsService.getNextId();
        DatastoreService ds = DatastoreServiceFactory.getDatastoreService();

        Key key = KeyFactory.createKey(BbsMessage.class.getSimpleName(), id);
        Transaction tx = Datastore.beginTransaction();

        try {
            ds.get(tx, key);
        } catch (EntityNotFoundException e) {

            BbsMessage bbs = new BbsMessage();
            bbs.setId(id);
            bbs.setKey(key);
            bbs.setInsertDate(new Date());
            BeanUtil.copy(request, bbs);

            try {
                Datastore.put(tx, bbs);
                tx.commit();
            }catch (ConcurrentModificationException e2) {
                requestScope("gmnMessage","排他エラー");
                if (tx.isActive()) {
                    tx.rollback();
                }

            }catch (Exception e2) {
                e.printStackTrace();
                requestScope("gmnMessage","システムエラー:" + e.getMessage());
            }


        }


        requestScope("processTime",timer.getProcessTimeMills());

        return redirect(basePath);
    }

    protected boolean validate() {
        Validators v = new Validators(request);
        v.add("userName", v.required());
        v.add("content", v.required());
        return v.validate();
    }
}